package VL::MigratePackage;

use 5.008008;
use strict;
use warnings;

require Exporter;

our @ISA = qw(Exporter);

# Items to export into callers namespace by default. Note: do not export
# names by default without a very good reason. Use EXPORT_OK instead.
# Do not simply export all your public functions/methods/constants.

# This allows declaration	use VL::MigratePackage ':all';
# If you do not need this, moving things directly into @EXPORT or @EXPORT_OK
# will save memory.
our %EXPORT_TAGS = ( 'all' => [ qw(
	
) ] );

our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );

our @EXPORT = qw( install
instDeps
	
);

our $VERSION = '0.01';

use Cwd qw(chdir getcwd);
use File::Find::Rule;
use File::Basename;
use Getopt::Std;
use LWP::Simple;
use Memoize;
use Net::FTP::Recursive;
use Log::Dispatch;
use Log::Dispatch::File;


#------------------------------------------------------------------------------
# Logger
#------------------------------------------------------------------------------ 
my $date = localtime;
my $dispatcher = Log::Dispatch->new;

$dispatcher->add( Log::Dispatch::File->new( name => 'vlmigrate',
                                            min_level => 'debug',
					    mode => 'append',
	                                    filename => 'vlmigrate.log' ) );

sub log_success {
	my $package = shift;
	$dispatcher->info("$date [ $package ]: Compiled.\n");
}

sub log_fail {
	my $package = shift;
	$dispatcher->error("$date [ $package ]: Compilation failed.\n");
	die "$package: error executing SlackBuild.\n";
}

sub log_sb_missing {
	my $package = shift;
	$dispatcher->critical("$date [ $package ]: SlackBuild not found.\n");
	die "$package: Missing SlackBuild.\n";
}
# End Logger ------------------------------------------------------------------

#------------------------------------------------------------------------------
# Install packages
# -----------------------------------------------------------------------------

sub installpkg {
	my $package = shift;
	system("installpkg $package");
	return $?;
}

sub slapt_get {
	my $package = shift;
	system("slapt-get -i $package --no-dep -y");
	return $?;
}

# End Install packages --------------------------------------------------------

our @instDeps;

sub instDeps {
	return (@instDeps);
}

sub installedpk { 
	my %b =  map {
		my @x = split /-/;
		my $clave = join '-', @x[0 .. @x-4];
		{ $clave => $x[-3] }
	} `ls /var/log/packages/`;
	return %b;
} 

sub install{
	my $package = shift || die "package parameter needeed $!\n";
	my $cb  = shift ;
	my $tab = shift;
	my %installedPkgs = installedpk;
#http://vectorlinux.osuosl.org/veclinux-6.0/source/extra
#my %repos = ( extra => , packages => , testing => ); 
	my @repos = qw(extra packages testing);
	my $version;
	my $found ;
	my $location;
	my %deps;
	foreach  ( @repos ) {
		my $content = get("http://vectorlinux.osuosl.org/veclinux-6.0/$_/PACKAGES.TXT");
		#print "$_\n";
		if ($content =~ m/PACKAGE NAME:\s*$package-([^\-]+)-[^\r\n]*\n\s*PACKAGE LOCATION:\s*(\S+)[^\r\n]*\n[^\r\n]*\n[^\r\n]*\n\s*PACKAGE REQUIRED:\s+([^\r\n]*)/i){
			$found = $_;
			$version = $1;
			$location = $2;
			#print "FOUND $3\n";
			$cb->($tab, "FOUND $3");
			%deps = split (/\s*>=\s*|\s*,\s*|\s*\|\s*/, $3); #create a hash with namedep => version

			for ( keys %deps ){ 
				if (exists $installedPkgs{$_}) {
					print "$_ already installed\n";
					delete($deps{$_}); 
				}
				else{
					print "           $_ not installed\n";
					my $ret = install($_ ,$cb, $tab.'  ');
					if (!$ret) { die "Unmet dependency: $_\n";}
					push @instDeps , $_; 
					print "installed\n";
				}
				#print "sleep\n";
				$cb->($tab, "$_ processed");
				sleep(1);
			} 
			#print "\n" , keys %deps , "\n";
		}
	}
	if ($found){
		#package is already built for 6.0
		my $ipk = installpkg($package);
		my $slp = slapt_get($package) if ($ipk);
		if ($slp) {
		print "FOUND! $package in $found $version $location\n";
		my $dest =createTree($package, $version);
		seekSource($package, $version, $found, $location, $dest);
		my @finder= new File::Find::Rule()->file()
		                              ->name( "*.SlackBuild" )
									  ->in( getcwd().'/'.$package );

		my $currpwd = getcwd();
		chdir(dirname((sort (@finder))[-1], "\n"));  # change cwd to the dir where last slackbuild resides
		if (-e "$package.SlackBuild") {
			system("sh $package.SlackBuild");
			if ($?) { 
				log_fail($package);
		       	}
		}
		
		else { 
			log_sb_missing($package);
	       	}

		system("installpkg ../*tlz");
		
		if (! $?) { log_success($package); }

		system("mv ../*tlz $currpwd");
		chdir($currpwd);
		#execute shellscript
	}
	}
	print "Package $package found? $found\n";
	return $found;
}

sub createTree {#{{{
	my	( $package , $version)	= @_;
	my $cwd =getcwd;
	mkdir "$cwd/$package";
	mkdir "$cwd/$package/$version";
	mkdir "$cwd/$package/$version/src";
	return  "$cwd/$package/$version/src";
}	# ----------  end of subroutine createTree  ----------#}}}


sub seekSource {#{{{
	my	( $package,$version, $repo , $location, $dest)	= @_;
#ftp://ftp.osuosl.org/pub/vectorlinux/veclinux-6.0/extra/x-apps/
	my $ftp = Net::FTP::Recursive->new("ftp.osuosl.org", Passive =>1) or die "Cannot connect to some.host.name: $@";
	$ftp->login("anonymous");
	$ftp->binary;
	$ftp->cwd("/pub/vectorlinux/veclinux-6.0/source/$repo/$location/$package");
	my $currdir = getcwd();
#TODO	crear tempdir con use File::Temp y mover archivos uno a uno.
	chdir (getcwd().'/'. $package.'/'.$version.'/src') or die "Could not chdir \n";
	$ftp->rget();
	$ftp->quit;
	chdir($currdir);
	return ;
}	# ----------  end of subroutine seekSource  ----------#}}}





# Preloaded methods go here.

1;
__END__
# Below is stub documentation for your module. You'd better edit it!

=head1 NAME

VL::MigratePackage - Perl extension for blah blah blah

=head1 SYNOPSIS

  use VL::MigratePackage;
  blah blah blah

=head1 DESCRIPTION

Stub documentation for VL::MigratePackage, created by h2xs. It looks like the
author of the extension was negligent enough to leave the stub
unedited.

Blah blah blah.

=head2 EXPORT

None by default.



=head1 SEE ALSO

Mention other useful documentation such as the documentation of
related modules or operating system documentation (such as man pages
in UNIX), or any relevant external documentation such as RFCs or
standards.

If you have a mailing list set up for your module, mention it here.

If you have a web site set up for your module, mention it here.

=head1 AUTHOR

Kidd, E<lt>kidd@slackware.lanE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2008 by Kidd

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.8 or,
at your option, any later version of Perl 5 you may have available.


=cut
